"""
pip install fastapi uvicorn
"""
import os
import argparse
import uvicorn
from loguru import logger
from contextlib import asynccontextmanager
from fastapi import (
    FastAPI, 
    responses, 
    status, 
)
from fastapi.middleware.gzip import GZipMiddleware


@asynccontextmanager
async def lifespan(app: FastAPI):
    # 应用启动时可以添加初始化逻辑
    logger.info("应用启动")
    yield
    # 应用关闭时可以添加清理逻辑
    logger.info("应用关闭")


# 初始化 FastAPI 应用
docs = os.getenv('API_DOCS')
app = FastAPI(
    title="Health Check API",
    lifespan=lifespan,
    docs_url=docs if docs is None else '/docs',
    redoc_url=docs if docs is None else '/redoc',
)


@app.head("/health", response_class=responses.PlainTextResponse)
async def health():
    """
    健康检测接口
    使用HEAD请求方式
    响应200代表健康，500代表失效
    """
    if True:
        logger.info("健康检查通过")
        return responses.PlainTextResponse(status_code=status.HTTP_200_OK)
    else:
        logger.error("健康检查失败")
        return responses.PlainTextResponse(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR)


def fastapi_start(port: int, gziplevel: int):
    # 添加压缩中间件
    app.add_middleware(
        GZipMiddleware, 
        minimum_size=500, 
        compresslevel=gziplevel
    )

    uvicorn.run(
        app,
        host="0.0.0.0",
        port=port,
        loop='asyncio'
    )


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Health Check API")
    parser.add_argument('-p', '--port', type=int, default=1001, help='API端口')
    args = parser.parse_args()
    fastapi_start(port=args.port, gziplevel=3)
